﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using C1.Silverlight.DataGrid;
using CommunitySystem.SystemService;
using System.Reflection;
using System.Collections.ObjectModel;
using CommunitySystem.DataService;
using CommunitySystem.Ctrls;
using System.ComponentModel;

namespace CommunitySystem
{
    public delegate void OnSelectionChangedEvent(object sender, object NewValue, object OldValue);
    public class DictTextBox : ContentControl, INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        public void NotifyPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this,
                    new PropertyChangedEventArgs(propertyName));
            }
        }

        private PopDirection _Direction = PopDirection.DOWN;

        public PopDirection Direction
        {
            get { return _Direction; }
            set { _Direction = value; }
        }
          


        public static DependencyProperty FieldProperty;

        public string Field
        {
            get
            {
                return (string)base.GetValue(FieldProperty);
            }
            set
            {
                base.SetValue(FieldProperty, value);
                this.OnApplyTemplate();
            }
        }

        private bool _AddEmptyValue;

        public bool AddEmptyValue
        {
            get { return _AddEmptyValue; }
            set { _AddEmptyValue = value; }
        }


        public object DataContent
        {
            get { return base.DataContext; }
            set
            {
                base.DataContext = value;
                this.NotifyPropertyChanged("DataContent");
            }
        }


        public event OnSelectionChangedEvent OnSelectionChanged;

        private string _SelectValue = null;
        public string SelectValue
        {
            get { return _SelectValue; }

            set
            {
                if (_SelectValue != value)
                {
                    object oldvalue = _SelectValue;
                    _SelectValue = value;
                    this.NotifyPropertyChanged("SelectValue");
                    if (OnSelectionChanged != null)
                    {
                        OnSelectionChanged(this, value, oldvalue);
                    }
                }
            }
        }

        /// <summary>
        /// 选中项，用来与TextBox进行绑定
        /// </summary>
        private DataService.DataDictionaryItemModel _SelectItem = null;
        public DataService.DataDictionaryItemModel SelectItem
        {
            get { return _SelectItem; }
            set {
                if (_SelectItem != value)
                {
                    _SelectItem = value;
                    this.NotifyPropertyChanged("SelectItem");
                }
            }
        }

        protected override void OnContentChanged(object oldContent, object newContent)
        {
            base.OnContentChanged(oldContent, newContent);
            if (null == newContent || string.IsNullOrEmpty(Field))
                return;
            PropertyInfo pi = newContent.GetType().GetProperty(Field);
            object obj = pi.GetValue(newContent, null);
            C1DataGrid cg = (C1DataGrid)this.GetTemplateChild("DataGrid1");
            ObservableCollection<CommunitySystem.DataService.DataDictionaryItemModel> Items = cg.ItemsSource as ObservableCollection<CommunitySystem.DataService.DataDictionaryItemModel>;
            CommunitySystem.DataService.DataDictionaryItemModel item = null;
            switch (DictResultType)
            {
                case DictResultType.ID:
                    item = Items.Where(c => c.Id == (int)obj).FirstOrDefault();
                    break;

                case DictResultType.Code:
                    item = Items.Where(c => c.DictCode == obj.ToString()).FirstOrDefault();
                    break;
                case DictResultType.Name:
                    item = Items.Where(c => c.DictValue == obj.ToString()).FirstOrDefault();
                    break;
            }
            cg.SelectedItem = item;

        }

        static DictTextBox()
        {

            FieldProperty = DependencyProperty.Register("Field",
                                           typeof(string),
                                           typeof(DictTextBox),
                                           new PropertyMetadata("默认属性值", new PropertyChangedCallback(DictTextBox.OnFieldPropertyChanged)));
        }

        private string[] _Parameter;
        /// <summary>
        /// 参数的书写格式为: param=value
        /// Sql中的参数书写格式为: column=:param
        /// </summary>
        public string[] Parameter
        {
            get { return _Parameter; }
            set
            {
                _Parameter = value;
                foreach (string s in _Parameter)
                {
                    _ParamString += s + ";";
                }
                this.OnApplyTemplate();
            }
        }

        private string _ParamString = string.Empty;

        private CommunitySystem.DataService.DataServiceClient client = null;

        private static void OnFieldPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            (d as DictTextBox).OnFieldPropertyChanged(e);
        }

        void OnFieldPropertyChanged(DependencyPropertyChangedEventArgs e)
        {
            try
            {
                //TextBlock BgTextBlock = this.GetTemplateChild("ButtonCaption") as TextBlock;
                //BgTextBlock.Text = e.NewValue as string;
            }
            catch (Exception ex)
            {
                string ks = ex.ToString();
            }

        }

        private string _DictCode;

        public string DictCode
        {
            get { return _DictCode; }
            set { _DictCode = value; }
        }

        private string _DictSql;

        public string DictSql
        {
            get { return _DictSql; }
            set { _DictSql = value; }
        }


        private bool _WriteValueWithParent;

        public bool WriteValueWithParent
        {
            get { return _WriteValueWithParent; }
            set { _WriteValueWithParent = value; }
        }
        

        private bool _IsNoNLeafSelectable = false;

        public bool IsNoNLeafSelectable
        {
            get { return _IsNoNLeafSelectable; }
            set { _IsNoNLeafSelectable = value; }
        }


        private DictViewType _DictViewType;

        public DictViewType DictViewType
        {
            get { return _DictViewType; }
            set { _DictViewType = value; }
        }

        private DictResultType _DictResultType;

        public DictResultType DictResultType
        {
            get { return _DictResultType; }
            set { _DictResultType = value; }
        }


        public DictTextBox()
        {
            this.DefaultStyleKey = typeof(DictTextBox);
            client = new DataServiceClient();
            // this.SetBinding(FrameworkElement.DataContextProperty, new System.Windows.Data.Binding("DataContent") { Mode = System.Windows.Data.BindingMode.TwoWay, Source = this });
            this.Loaded += new RoutedEventHandler(DictTextBox_Loaded);
        }

        void DictTextBox_Loaded(object sender, RoutedEventArgs e)
        {

        }

        #region 控件集合
        private Image imgRefresh = null;//刷新按钮
        private TreeView tw = null;
        private CommunitySystem.DataService.DataDictionaryModel ResultValue = null;
        private BusyIndicator indicator = null;
        private TextBox tbSearch = null;
        private System.Windows.Controls.Primitives.Popup pop = null;
        private TextBox tb = null;
        Button btton = null;
        #endregion

        private System.Windows.Threading.DispatcherTimer timer = null;
        private object _PreDataContext = null;
        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();
            btton = (Button)this.GetTemplateChild("Button1");
            if (btton != null)
            {
                FrameworkElement fe = this;
                while (GetParentUI(fe) != null)
                {
                    fe = fe.Parent as FrameworkElement;
                    fe.MouseLeftButtonDown += new MouseButtonEventHandler(fe_MouseLeftButtonDown);
                }

              
                btton.Click -= new RoutedEventHandler(btton_Click);
                btton.Click += new RoutedEventHandler(btton_Click);
                tb = (TextBox)this.GetTemplateChild("TextBox1");

                if (timer == null)
                {
                    timer = new System.Windows.Threading.DispatcherTimer();
                    timer.Interval = new TimeSpan(0, 0, 0, 0, 100);
                    timer.Tick += new EventHandler(timer_Tick);
                    timer.Start();
                }
                //System.Windows.Data.Binding binding = new System.Windows.Data.Binding() { Mode= System.Windows.Data.BindingMode.TwoWay };
                //binding.ConverterParameter = 

                //tb.SetBinding(TextBox.TextProperty, new System.Windows.Data.Binding() { Mode = System.Windows.Data.BindingMode.TwoWay, 
                //    Path = new PropertyPath("SelectValue"), 
                //    Source = this, ValidatesOnDataErrors = true, ValidatesOnNotifyDataErrors = true });
                this.LostFocus -= new RoutedEventHandler(DictTextBox_LostFocus);
                this.LostFocus += new RoutedEventHandler(DictTextBox_LostFocus);
                C1DataGrid dg = (C1DataGrid)this.GetTemplateChild("DataGrid1");
                pop = (System.Windows.Controls.Primitives.Popup)this.GetTemplateChild("Popup1");
                //pop.LostFocus -= new RoutedEventHandler(DictTextBox_LostFocus);
                //pop.LostFocus += new RoutedEventHandler(DictTextBox_LostFocus);
                //pop.MouseLeave += new MouseEventHandler(pop_MouseLeave);
                if (dg != null)
                {
                    dg.SelectionChanged -= new EventHandler<DataGridSelectionChangedEventArgs>(dg_SelectionChanged);
                    dg.SelectionChanged += new EventHandler<DataGridSelectionChangedEventArgs>(dg_SelectionChanged);
                }
                imgRefresh = (Image)this.GetTemplateChild("btRefresh");
                imgRefresh.MouseLeftButtonDown -= new MouseButtonEventHandler(imgRefresh_MouseLeftButtonDown);
                imgRefresh.MouseLeftButtonDown += new MouseButtonEventHandler(imgRefresh_MouseLeftButtonDown); //+= new RoutedEventHandler(btnRefresh_Click);
                tbSearch = (TextBox)this.GetTemplateChild("TextBox2");
                tbSearch.TextChanged -= new TextChangedEventHandler(tbSearch_TextChanged);
                tbSearch.TextChanged += new TextChangedEventHandler(tbSearch_TextChanged);
                indicator = (BusyIndicator)this.GetTemplateChild("xBusy");
                indicator.IsBusy = true;
                indicator.BusyContent = "Loading...";                
                client.GetDictModelCompleted -= new EventHandler<GetDictModelCompletedEventArgs>(client_GetDictModelCompleted);
                client.GetDictModelCompleted += new EventHandler<GetDictModelCompletedEventArgs>(client_GetDictModelCompleted);
                if (CommunitySystem.Common.InitialDictionary.Dict.Keys.Where(c => c.Equals(DictCode)).Count() <= 0)
                {
                    //client.GetDictModelAsync(DictCode, _ParamString);
                    CommunitySystem.Common.InitialDictionary init = new Common.InitialDictionary();
                    init.RefreshDictionary(DictCode, _ParamString, this);
                }
                else
                {
                    
                    client_GetDictModelCompleted(null, new GetDictModelCompletedEventArgs(new object[1] { CommunitySystem.Common.InitialDictionary.Dict.Where(c => c.Key.Equals(DictCode)).FirstOrDefault().Value }, null, false, null));
                }

            }
        }

        void timer_Tick(object sender, EventArgs e)
        {
            if (_PreDataContext != this.DataContext && this.DataContext != null && this.ResultValue != null)
            {
                InitailControl(ResultValue);
                this.timer.Tick -= new EventHandler(timer_Tick);
            }
        }

        void fe_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            pop.IsOpen = false;
        }

        FrameworkElement GetParentUI(FrameworkElement ui)
        {
            return ui.Parent as FrameworkElement;
        }
       
       

        void pop_MouseLeave(object sender, MouseEventArgs e)
        {
            pop.IsOpen = false;
        }

        void DictTextBox_MouseLeave(object sender, MouseEventArgs e)
        {
            pop.IsOpen = false;
        }





        void DictTextBox_LostFocus(object sender, RoutedEventArgs e)
        {
            pop.IsOpen = false;
        }

        /// <summary>
        /// 刷新按钮动作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void imgRefresh_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            indicator.IsBusy = true;
            //client.GetDictModelAsync(DictCode, _ParamString);
            CommunitySystem.Common.InitialDictionary init = new Common.InitialDictionary();
            init.RefreshDictionary(DictCode, _ParamString, this);
        }

        /// <summary>
        /// 搜索框
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void tbSearch_TextChanged(object sender, TextChangedEventArgs e)
        {
            string text = tbSearch.Text;
            if (!string.IsNullOrEmpty(text))
            {
                CommunitySystem.DataService.DataDictionaryModel data = new CommunitySystem.DataService.DataDictionaryModel() { IsTree = ResultValue.IsTree };
                data.Item = new ObservableCollection<CommunitySystem.DataService.DataDictionaryItemModel>
                    (ResultValue.Item.Where(c => c.DictCode.Contains(text) || c.DictPinYin.Contains(text) || c.DictValue.Contains(text)));
                InitailControl(data);
            }
            else
            {
                indicator.IsBusy = true;
                client.GetDictModelAsync(this.DictCode, _ParamString);
            }
        }



       public  void client_GetDictModelCompleted(object sender, GetDictModelCompletedEventArgs e)
        {
            indicator.IsBusy = false;
            ResultValue = e.Result;
            if (AddEmptyValue == true)
                ResultValue.Item.Add(new DataService.DataDictionaryItemModel() { Id = -1, DictCode = "Null", DictValue = "Null", DictPinYin = "Null", ParentId = 0 });
            if (e.Result == null || e.Result.Item.Count <= 0)
                return;
            InitailControl(ResultValue);
        }

        void InitailControl(CommunitySystem.DataService.DataDictionaryModel _ResultValue)
        {
            C1DataGrid dg = (C1DataGrid)this.GetTemplateChild("DataGrid1");
            #region 树型数据字典

            if (_ResultValue.IsTree)
            {
                Grid g = (Grid)this.GetTemplateChild("Grid1");
                if (g != null && g.Children.Count >= 2)
                {
                    g.Children.RemoveAt(0);
                }
                tw = new TreeView();
                tw.Margin = new Thickness(0, 0, 0, 29);
                //tw.MouseLeftButtonDown -= new MouseButtonEventHandler(tvi_MouseLeftButtonDown);
                //tw.MouseLeftButtonDown += new MouseButtonEventHandler(tvi_MouseLeftButtonDown);
                g.Children.Insert(0, tw);
                var parentItem = from u in _ResultValue.Item
                                 orderby u.ParentId
                                 select u;
                var i = parentItem.FirstOrDefault();
                //foreach (var i in parentItem.FirstOrDefault())
                //{
                    TreeViewItem tvi = new TreeViewItem();//{ Header = "[" + i.Id + "]" + i.DictCode };
                    tvi.DataContext = i;
                    AddTreeNode(tvi, i.Id, _ResultValue.Item);
                    if (IsNoNLeafSelectable == false)//非叶子节点不可以选择
                    {
                        if (tvi.Items.Count <= 0)//叶子节点可以点击
                        {
                            AddTreeHead(tvi, i, true);
                            //HyperlinkButton link = new HyperlinkButton() { Content = "[" + i.Id + "]" + i.DictCode };
                            //link.Click += new RoutedEventHandler(link_Click);
                            //tvi.Header = link;
                            //tvi.MouseLeftButtonDown += new MouseButtonEventHandler(tvi_MouseLeftButtonDown);
                        }
                        else
                        {
                            //tvi.Header = "[" + i.Id + "]" + i.DictCode;
                            AddTreeHead(tvi, i, false);
                        }
                    }
                    else//所有节点都可以选择
                    {
                        //HyperlinkButton link = new HyperlinkButton() { Content = "[" + i.Id + "]" + i.DictCode };
                        //link.Click += new RoutedEventHandler(link_Click);
                        //tvi.Header = link;
                        AddTreeHead(tvi, i, true);
                    }
                    tw.Items.Add(tvi);
               // }
                if (!string.IsNullOrEmpty(Field) && this.DataContext != null)
                {
                    object obj = this.DataContext;
                    PropertyInfo pi = obj.GetType().GetProperty(Field);
                    if (pi != null)
                    {
                        object value = pi.GetValue(obj, null);
                        if (value == null || string.IsNullOrEmpty(value.ToString()))
                        {
                            SetText(null);
                            return;
                        }
                        CommunitySystem.DataService.DataDictionaryItemModel SelectItem = null;
                        switch (DictResultType)
                        {
                            case DictResultType.ID:
                                SelectItem = _ResultValue.Item.Where(c => c.Id == (int)value).FirstOrDefault();
                                break;
                            case DictResultType.Code:
                                SelectItem = _ResultValue.Item.Where(c => c.DictCode == value.ToString()).FirstOrDefault();
                                break;
                            case DictResultType.Name:
                                SelectItem = _ResultValue.Item.Where(c => c.DictValue == value.ToString()).FirstOrDefault();
                                break;
                        }
                        SetText(SelectItem);
                    }
                }

                return;
            }
            #endregion

            #region 普通数据字典
            dg.Columns[0].Header = "编码";
            dg.Columns[1].Header = "名称";
            //dg.Columns[0].
            dg.ItemsSource = _ResultValue.Item;
            //初始化如果有值， 自动绑定上

            if (!string.IsNullOrEmpty(Field) && this.DataContext != null)
            {
                object obj = this.DataContext;
                PropertyInfo pi = obj.GetType().GetProperty(Field);
                if (pi != null)
                {
                    object value = pi.GetValue(obj, null);
                    if (value == null || string.IsNullOrEmpty(value.ToString()))
                    {
                        SetText(null);
                        return;
                    }
                    CommunitySystem.DataService.DataDictionaryItemModel SelectItem = null;
                    switch (DictResultType)
                    {
                        case DictResultType.ID:
                            SelectItem = _ResultValue.Item.Where(c => c.Id == (int)value).FirstOrDefault();
                            break;
                        case DictResultType.Code:
                            SelectItem = _ResultValue.Item.Where(c => c.DictCode == value.ToString()).FirstOrDefault();
                            break;
                        case DictResultType.Name:
                            SelectItem = _ResultValue.Item.Where(c => c.DictValue == value.ToString()).FirstOrDefault();
                            break;
                    }
                    //SetText(SelectItem);
                    if (_WriteValueWithParent == true && this.DictResultType == DictResultType.Name && this.DictViewType == DictViewType.Name)
                    {
                        CommunitySystem.DataService.DataDictionaryItemModel newItem = new CommunitySystem.DataService.DataDictionaryItemModel() { DictValue = value.ToString() };
                        SetText(newItem);
                    }
                    else
                        SetText(SelectItem);
                }
            }
            #endregion
        }

        void link_Click(object sender, RoutedEventArgs e)
        {
            TreeView dg = tw;
            if (dg.SelectedItem != null)
            {
                //SetText((dg.SelectedItem as TreeViewItem).DataContext as CommunitySystem.DataService.DataDictionaryItemModel);
                if (_WriteValueWithParent == true && this.DictResultType == DictResultType.Name && this.DictViewType == DictViewType.Name)
                {
                    var item = (dg.SelectedItem as TreeViewItem).DataContext as CommunitySystem.DataService.DataDictionaryItemModel;
                    CommunitySystem.DataService.DataDictionaryItemModel newItem = new CommunitySystem.DataService.DataDictionaryItemModel() { DictValue = item.DictValue };
                    while (ResultValue.Item.Where(c => c.Id == item.ParentId && c.ParentId != 0).Count() > 0)
                    {
                        item = ResultValue.Item.Where(c => c.Id == item.ParentId).FirstOrDefault();
                        newItem.DictValue = item.DictValue + newItem.DictValue;
                    }
                    SetText(newItem);
                }
                else
                    SetText((dg.SelectedItem as TreeViewItem).DataContext as CommunitySystem.DataService.DataDictionaryItemModel);
            }

            pop.IsOpen = false;
        }

        void AddTreeHead(TreeViewItem tvi, CommunitySystem.DataService.DataDictionaryItemModel item, bool Selectedable)
        {
            HyperlinkButton hlb = new HyperlinkButton();
            hlb.Click += new RoutedEventHandler(link_Click);
            switch (this.DictViewType)
            {
                case Ctrls.DictViewType.ID:
                    if (Selectedable)
                    {
                        hlb.Content = item.Id;
                        tvi.Header = hlb;
                    }
                    else
                        tvi.Header = item.Id;
                    break;
                case Ctrls.DictViewType.Code:
                    if (Selectedable)
                    {
                        hlb.Content = item.DictCode;
                        tvi.Header = hlb;
                    }
                    else
                        tvi.Header = item.DictCode;
                    break;
                case Ctrls.DictViewType.Name:
                    if (Selectedable)
                    {
                        hlb.Content = item.DictValue;
                        tvi.Header = hlb;
                    }
                    else
                        tvi.Header = item.DictValue;
                    break;
                case Ctrls.DictViewType.IDAndName:
                    if (Selectedable)
                    {
                        hlb.Content = "[" + item.Id + "]" + item.DictValue;
                        tvi.Header = hlb;
                    }
                    else
                        tvi.Header = "[" + item.Id + "]" + item.DictValue;
                    break;
                case Ctrls.DictViewType.CodeAndName:
                    if (Selectedable)
                    {
                        hlb.Content = "[" + item.DictCode + "]" + item.DictValue;
                        tvi.Header = hlb;
                    }
                    else
                        tvi.Header = "[" + item.DictCode + "]" + item.DictValue;
                    break;
            }
        }

        void AddTreeNode(TreeViewItem pitem, int pid, ObservableCollection<CommunitySystem.DataService.DataDictionaryItemModel> source)
        {
            foreach (var i in source.Where(c => c.ParentId == pid))
            {
                TreeViewItem tvi = new TreeViewItem();//{ Header = "[" + i.Id + "]" + i.DictCode };
                tvi.DataContext = i;
                AddTreeNode(tvi, i.Id, source);
                //if (tvi.Items.Count <= 0)//叶子节点可以点击
                //{
                //    tvi.MouseLeftButtonDown += new MouseButtonEventHandler(tvi_MouseLeftButtonDown);
                //}

                if (IsNoNLeafSelectable == false)//非叶子节点不可以选择
                {
                    if (tvi.Items.Count <= 0)//叶子节点可以点击
                    {
                        AddTreeHead(tvi, i, true);
                        //HyperlinkButton link = new HyperlinkButton() { Content = "[" + i.Id + "]" + i.DictCode };
                        //link.Click += new RoutedEventHandler(link_Click);
                        //tvi.Header = link;
                        //tvi.MouseLeftButtonDown += new MouseButtonEventHandler(tvi_MouseLeftButtonDown);
                    }
                    else
                    {
                        //tvi.Header = "[" + i.Id + "]" + i.DictCode;
                        AddTreeHead(tvi, i, false);
                    }
                }
                else//所有节点都可以选择
                {
                    //HyperlinkButton link = new HyperlinkButton() { Content = "[" + i.Id + "]" + i.DictCode };
                    //link.Click += new RoutedEventHandler(link_Click);
                    //tvi.Header = link;
                    AddTreeHead(tvi, i, true);
                }
              
                pitem.Items.Add(tvi);
            }
        }

        /// <summary>
        /// 
        /// </summary>        
        /// <param name="item"></param>
        void SetText(CommunitySystem.DataService.DataDictionaryItemModel item)
        {

            if (tb == null)
                return;
            if (item == null)
            {
                tb.Text = "";
                SelectValue = null;
                return;
            }
            switch (DictViewType)
            {
                case DictViewType.ID:
                    tb.Text = item.Id + "";

                    break;
                case DictViewType.Code:
                    tb.Text = item.DictCode;
                    break;
                case DictViewType.Name:
                    tb.Text = item.DictValue;
                    break;
                case DictViewType.CodeAndName:
                    tb.Text = item.DictCode + ":" + item.DictValue;
                    break;               
                case DictViewType.IDAndName:
                    tb.Text = item.Id + ":" + item.DictValue;
                    break;
            }
            object context = this.DataContext;
            if (context == null || string.IsNullOrEmpty(Field))
                return;
            PropertyInfo pi = context.GetType().GetProperty(Field); ;
            switch (DictResultType)
            {

                case DictResultType.ID:
                    pi.SetValue(context, item.Id, null);
                    SelectValue = item.Id + "";
                    break;
                case DictResultType.Code:
                    pi.SetValue(context, item.DictCode, null);
                    SelectValue = item.DictCode;
                    break;
                case DictResultType.Name:
                    pi.SetValue(context, item.DictValue, null);
                    SelectValue = item.DictValue;
                    break;
            }
            this.SelectItem = item;
        }

      

        void dg_SelectionChanged(object sender, DataGridSelectionChangedEventArgs e)
        {
            C1DataGrid dg = sender as C1DataGrid;
            if (dg.SelectedItem != null)
            {
                SetText(dg.SelectedItem as CommunitySystem.DataService.DataDictionaryItemModel);
            }
            btton_Click(btton, null);
        }

        void btton_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Controls.Primitives.Popup pop = (System.Windows.Controls.Primitives.Popup)this.GetTemplateChild("Popup1");
            pop.IsOpen = !pop.IsOpen;
            
            Button btn1 = (Button)sender;

            GeneralTransform gtf = btn1.TransformToVisual(btn1);
            Point pPostion = gtf.Transform(new Point(0, 0));
            pop.HorizontalOffset = pPostion.X;
            pop.VerticalOffset = pPostion.Y + btn1.Height;
            if (pop.IsOpen == true && Direction == PopDirection.UP)
            {
                pop.VerticalOffset = pPostion.Y - 255;
            }
           
        }

    }

    public enum PopDirection
    {
        UP = 1,
        DOWN = 2
    }
}
